"use client";

import { useApiMutation } from "@/hooks/use-api-mutation";
import { api } from "@/convex/_generated/api";

import { formatDistanceToNow } from "date-fns";


import Link from "next/link";
import Image from "next/image";
import { Overlay } from "./overlay";

import { Footer } from "./footer";
import { useAuth } from "@clerk/nextjs";
import { Skeleton } from "@/components/ui/skeleton";
import { Actions } from "@/components/actions";
import { MoreHorizontal } from "lucide-react";
import { Id } from "@/convex/_generated/dataModel";
import { toast } from "sonner";




interface BoardCardProps {
    id: string;
    title: string;
    authorName: string;
    authorId: string;
    createdAt: number;
    imageUrl: string;
    orgId: string;
    isFavorite: boolean;
}
export const BoardCard = (
    { id, title, authorName, authorId, createdAt, imageUrl, orgId, isFavorite }: BoardCardProps
) => {
    // 从 useAuth Hook 中获取当前用户的 userId
    const { userId } = useAuth();

    // 根据当前用户是否为作者，设置 authorLabel 的值
    const authorLabel = userId === authorId ? "You" : authorName;

    // 格式化 createdAt 到现在的时间距离，并添加后缀
    const createdAtLabel = formatDistanceToNow(createdAt, {
        addSuffix: true,
    });


    const {
        mutate: onFavorite,
        pending: pendingFavorite,
    } = useApiMutation(api.board.favorite);
    const {
        mutate: onUnFavorite,
        pending: pendingUnFavorite,
    } = useApiMutation(api.board.unfavorite);


    if (!authorName) {
        return <Skeleton className="h-full w-full" />;
    }

    const toggleFavorite = () => {
        if (isFavorite) {
            onUnFavorite({ id: id as Id<"boards"> }).catch(() =>
                toast.error("Failed to unfavorite board")
            );
        } else {
            onFavorite({ id: id as Id<"boards">, orgId }).catch(() =>
                toast.error("Failed to favorite board")
            );
        }
    };

    return (
        <Link href={`/board/${id}`}>
            {/* 外层链接容器，导航到动态路径 /board/${id} */}
            {/* group代表将子元素和父元素关联,用于悬停,设置元素宽高比/flex用于设置布局,flex-col是垂直布局 */}
            <div className="group aspect-[100/127] border rounded-lg flex flex-col justify-between overflow-hidden">
                {/* 内层容器，设置宽高比、边框、圆角、Flexbox布局等 */}
                {/* flex1表示填充剩余空间 */}
                <div className="relative flex-1 bg-amber-50">
                    {/* 图像组件，显示图像 */}
                    <Image
                        // 图像来源
                        src={imageUrl}
                        // 图像的替代文字
                        alt={title}

                        fill
                        // 图像的适应方式
                        className="object-fit"
                    />
                    <Overlay />
                    <Actions
                        id={id}
                        title={title}
                        side="right"
                    >
                        <button
                            className="absolute top-1 right-1 opacity-0 group-hover:opacity-100 transition-opacity px-3 py-2 outline-none">
                            <MoreHorizontal
                                className="text-white opacity-75 hover:opacity-100 transition-opacity"
                            />
                        </button>
                    </Actions>
                </div>
                <Footer
                    isFavorite={isFavorite}
                    title={title}
                    authorLabel={authorLabel}
                    createdAtLabel={createdAtLabel}
                    onClick={toggleFavorite}
                    disabled={pendingFavorite || pendingUnFavorite}
                />
            </div>
        </Link>
    )
}
BoardCard.Skeleton = function BoardCardSkeleton() {
    return (
        <div className="aspect-[100/127] rounded-lg overflow-hidden">
            {/* 外层容器，设置宽高比、圆角和溢出隐藏 */}
            <Skeleton className="h-full w-full" />
            {/* Skeleton 组件，设置高度和宽度为100% */}
        </div>
    );
};